package com.stu.wgt.test.service.Imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stu.wgt.test.bean.Admin;
import com.stu.wgt.test.mapper.UserMapper;
import com.stu.wgt.test.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wgt
 * @since 2024-01-20
 */
@Service
public class AdminServiceImpl extends ServiceImpl<UserMapper, Admin> implements AdminService {

    @Autowired
    UserMapper userMapper;

    // 查
    public List<Admin> selectAllUser() {
        return userMapper.selectList(null);
    }

    @Override
    public List<Admin> selectByUsername(String username) {
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.eq("username", username);
        return userMapper.selectList(qw);
    }

    @Override
    public List<Admin> selectById(int id) {
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.eq("id", id);
        return userMapper.selectList(qw);
    }

    @Override
    public IPage<Admin> searchUsers(String query, int pageNum, int pageSize) {
        Page<Admin> page = new Page<>(pageNum, pageSize); // 创建分页对象，指定当前页码和每页显示条数
        QueryWrapper<Admin> wrapper = new QueryWrapper<>(); // 创建查询条件对象
        wrapper.like("username", query); // 设置查询条件，这里使用模糊查询
        IPage<Admin> userPage = userMapper.selectPage(page, wrapper); // 执行分页查询
        return userPage;
    }

    // 删
    @Override
    public int deleteUser(int id) {
        return userMapper.deleteById(id);
    }

    // 改
    @Override
    public int updateUser(Admin admin) {
        QueryWrapper<Admin> qw = new QueryWrapper<Admin>();
        qw.eq("id", admin.getId());
        return userMapper.update(admin, qw);
    }

    //用户注册
    @Override
    public int register(Admin admin) {
        int isTrue = 0;
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.eq("username", admin.getUsername());
        if (userMapper.selectList(qw).isEmpty()) {
//            String rawPass = passwordEncoder.encode(user.getPassword());
//            user.setPassword(rawPass);
            isTrue = userMapper.insert(admin);
        }
        return isTrue;
    }

    // 登录
    @Override
    public boolean login(String username, String password) {
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.eq("username", username).eq("password", password);
        if (userMapper.selectCount(qw) == 1) {
            return true;
        }
        return false;
    }

}
